package com.cobalt4nt.photomap;
import java.io.IOException;
import java.util.List;

import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;

import com.cobalt4nt.photomap.MapActivity.PictureWithLocation;
import com.cobalt4nt.photomap.MapActivity.Scope;

public class GeocoderTask extends AsyncTask<Void, Integer, Address> {
	private PictureWithLocation picture;
	private Scope scope;
	private GeocodingActivity context;
	public GeocoderTask(GeocodingActivity context, PictureWithLocation picture, Scope scope) {
		this.context = context;
		this.picture = picture;
		this.scope = scope;
	}

	@Override
	protected Address doInBackground(Void... params) {
		StringBuilder sb = new StringBuilder();
		while(true) {
			sb.append(picture.get(scope));
			scope = scope.nextLarger();
			if(scope == null) {
				break;
			}
			sb.append(", ");
		}
		try {
			Geocoder geocoder = new Geocoder(context);
			List<Address> resultAddresses = geocoder.getFromLocationName(sb.toString(), 1);
			if(resultAddresses.size() > 0) {
				return resultAddresses.get(0);
			} else if(scope != Scope.SELF) {
				context.error("No addresses found");
			}
		} catch(IOException e) {
			context.error("No Internet Connection");
		}
		return null;
	}
	protected void onPostExecute(Address result) {
		context.alertGeocodingComplete(result, picture);
	}
}